package com.dslcode.cloud.common.enums;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;

import java.io.IOException;

/**
 * Created by dongsilin on 2017/9/30.
 * enum json 反序列化
 */
public class EnumJsonDeserializer<E extends IntEnum> extends JsonDeserializer<E> implements ContextualDeserializer {

    private E target;

    @Override
    public E deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {
        JsonNode node = jsonParser.getCodec().readTree(jsonParser);
        if (null == node) return null;
        return (E) target.fromJSON(node.toString());
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
        Class<E> clazz = (Class<E>) ctxt.getContextualType().getRawClass();
        target = clazz.getEnumConstants()[0];
        return this;
    }

}
